<?php
class WUploadFile{    
	private $cls_upload_dir = "/upload/";         // Directory to upload to.
	private $cls_filename = "";           // Name of the upload file.
	private $cls_tmp_filename = "";       // TMP file Name (tmp name by php).
	private $cls_max_filesize = 100; // Max file size.
	private $cls_filesize ="";            // Actual file size.
	private $cls_arr_ext_accepted = array(".gif",".jpg",".jpeg",'.sql');
	private $cls_file_exists = 0;         // Set to 1 to check if file exist before upload.
	private $cls_rename_file = 0;         // Set to 1 to rename file after upload.
	private $cls_file_rename_to = '';     // New name for the file after upload.
	private $cls_verbal = 0;              // Set to 1 to return an a string instead of an error code.

	function return_bytes($val) {
		$val = trim($val);
		$last = strtolower($val{strlen($val)-1});
		switch($last) {
			case 'g':
				$val *= 1024;
			case 'm':
				$val *= 1024;
			case 'k':
				$val *= 1024;
		}
		return $val;
	}
  /** constructor()
   **
   ** @para String File name
   ** @para String Temp file name
   ** @para Int File size
   ** @para String file rename to
  **/
	function WUploadFile( $file_name, $tmp_file_name, $file_size, $cls_rename_file = '' )
	{
		$this->cls_filename = $file_name;
		$this->cls_tmp_filename = $tmp_file_name;
		$this->cls_filesize = $file_size;
		$this->cls_rename_file = $cls_rename_file;
		$this->cls_max_filesize = $this->return_bytes(ini_get("upload_max_filesize"));
	}

  /** isUploadedFile()
   **
   ** Method to wrap php 4.0.3 is_uploaded_file fct
   ** It will return an error code if the file has not been upload to /tmp on the web server
   ** (look with phpinfo() fct where php store tmp uploaded file)
   ** @returns string
  **/
	function isUploadedFile()
	{
		if( is_uploaded_file( $this->cls_tmp_filename ) != true )
		{
			return "IS_UPLOADED_FILE_FAILURE";
		} 
		else 
		{
			return 1;
		}
	}

  /** setDir()
   **
   ** Method to set the directory we will upload to. 
   ** It will return an error code if the dir is not writable.
   ** @para String name of directory we upload to
   ** @returns string
  **/
	function setDir( $dir,$type )
	{
		$this->cls_upload_dir = DOCUMENTROOT.$dir;
		if(!file_exists($this->cls_upload_dir))
		{
			mkdir($this->cls_upload_dir);
		}
		if( !is_writable( $this->cls_upload_dir) )
		{
				return "DIRECTORY_FAILURE";
		} 
		elseif($type == 1) 
		{ 
			$this->cls_upload_dir = $this->cls_upload_dir . date("Ymd")  . "/";
			if(!file_exists($this->cls_upload_dir))
			{
				mkdir($this->cls_upload_dir);
			}
			return 1;
		}
		else 
			return 1;
	}

  /** checkExtension()
   **
   ** Method to check if we accept the file extension.
   ** @returns string
  **/
	function checkExtension()
	{
		// Check if the extension is valid
		if( !in_array( strtolower( strrchr( $this->cls_filename, "." )), $this->cls_arr_ext_accepted ))
		{
		  return "EXTENSION_FAILURE";
		} else 
		{
		  return 1;
		}
	}

  /** checkSize()
   **
   ** Method to check if the file is not to big.
   ** @returns string
  **/
	function checkSize()
	{
		if( $this->cls_filesize > $this->cls_max_filesize )
		{
			return "FILE_SIZE_FAILURE";
		} else {
		  	return 1;
		}
	}

  /** move()
   **
   ** Method to wrap php 4.0.3 fct move_uploaded_file()
   ** @returns string
  **/
	function move()
	{	
		if( move_uploaded_file( $this->cls_tmp_filename, $this->cls_upload_dir . $this->cls_filename ) == false )
		{
		  return "MOVE_UPLOADED_FILE_FAILURE";
		} 
		else 
		{
		  return 1;
		}
	}

  /** checkFileExists()
   **
   ** Method to check if a file with the same name exists in
   ** destination folder.
   ** @returns string
  **/
	function checkFileExists()
	{
		if( file_exists( $this->cls_upload_dir . $this->cls_filename ) )
		{
		  	return "FILE_EXISTS_FAILURE";
		} 
		else 
		{
		  	return 1;
		}
	}

  /** renameFile()
   **
   ** Method to rename the uploaded file.
   ** If no name was provided with the constructor, we use
   ** a random name.
   ** @returns string
  **/

/*以字母与数字生成的随机数重新为上传文件命名

	function renameFile()
	{
		// if no new name was provided, we use
		if( $this->cls_file_rename_to == '' )
		{
			$allchar = "abcdefghijklnmopqrstuvwxyz1234567890" ; 
			$this->cls_file_rename_to = "" ; 
			mt_srand (( double) microtime() * 1000000 ); 
			for ( $i = 0; $i<8 ; $i++ )
			{
				$this->cls_file_rename_to .= substr( $allchar, mt_rand (0,35), 1 ) ; 
			}
			$extension = strrchr( $this->cls_filename, "." );
			$this->cls_file_rename_to .= $extension;
			$this->cls_filename = $this->cls_file_rename_to;
		}
		else
			$this->cls_filename = $this->cls_file_rename_to;
	}
  */
  //以上传的年月日时分秒来为上传文件重新命名
 function renameFile()
	{
		// if no new name was provided, we use
		if( $this->cls_file_rename_to == '' )
		{
			$extension = strrchr( $this->cls_filename, "." );
			$this->cls_file_rename_to= date("Ymdhis").$extension;
			$this->cls_filename = $this->cls_file_rename_to;
		}
		else
			$this->cls_filename = $this->cls_file_rename_to;
	}
  /** upload()
   **
   ** Method to upload the file.
   ** This is the only method to call outside the class.
   ** @para String name of directory we upload to
   ** @returns void
  **/
	function upload( $dir,$type=0 )
	{
		$ret = $this->isUploadedFile();
		if( $ret != 1 )
		{
		  return $this->resultUpload( $ret );
		}
    	$ret = $this->setDir( $dir,$type );
	    if( $ret != 1 )
	    {
	      	return $this->resultUpload( $ret );
	    }
	    $ret = $this->checkExtension();
	    if( $ret != 1 )
	    {
	      	return $this->resultUpload( $ret );
	    }

	    $ret = $this->checkSize();
	    if( $ret != 1 )
	    {
	      	return $this->resultUpload( $ret );    
	    }
    	// check if we need to rename the file
		if( $this->cls_rename_file == 1 )
		{
			$this->renameFile();
			/*
			if( $ret != 1 )
			{
				return $this->resultUpload( $ret );    
			}
			*/
		}
		// if flag to check if the file exists is set to 1
	    if( $this->cls_file_exists == 1 )
	    {
	      	$ret = $this->checkFileExists();
			if( $ret != 1 )
			{
				return $this->resultUpload( $ret );    
			}
    	}
		// if we are here, we are ready to move the file to destination
		$ret = $this->move();
		if( $ret != 1 )
		{
		  	return $this->resultUpload( $ret );    
		}
    	
    	// if we are here, everything worked as planned :)
    	return $this->resultUpload( "SUCCESS" );
  }

  /** resultUpload()
   **
   ** Method that returns the status of the upload
   ** (You should put cls_verbal to 1 during debugging...)
   ** @para String Status of the upload
   ** @returns mixed (int or string)
  **/
	function resultUpload( $flag )
	{
		switch( $flag ){
		  case "IS_UPLOADED_FILE_FAILURE" : if( $this->cls_verbal == 0 ) return -1; else return "上传文件失败，无法保存到临时目录中。 <br><br>请确认是通过 HTTP POST 方式上传的文件或文件大小小于服务器允许上传的最大尺寸" . ini_get("upload_max_filesize") . "。";
		    break;
		  case "DIRECTORY_FAILURE"        : if( $this->cls_verbal == 0 ) return -2; else return "上传文件失败，<font color=red>".$this->cls_upload_dir."</font>目录不可写";
		    break;
		  case "EXTENSION_FAILURE"        : if( $this->cls_verbal == 0 ) return -3; else return "上传文件失败，不允许上传该种类型文件.";
		    break;
		  case "FILE_SIZE_FAILURE"        : if( $this->cls_verbal == 0 ) return -4; else return "上传文件失败，文件超过最大上传限制";
		    break;
		  case "FILE_EXISTS_FAILURE"      : if( $this->cls_verbal == 0 ) return -5; else return "上传文件失败，<font color=red>{$this->cls_filename}</font>已经存在";
		    break;
		  case "MOVE_UPLOADED_FILE_FAILURE" : if( $this->cls_verbal == 0 ) return -6; else return "上传文件失败，上传文件无法复制到指定文件夹中";
		    break;
		  case "RENAME_FAILURE"           : if( $this->cls_verbal == 0 ) return 2; else return "上传文件失败，上传文件改名失败";
		    break;
		  case "SUCCESS"                  : if( $this->cls_verbal == 0 ) return 1; else return "";
		    break;
		  default : echo "OUPS!! We do not know what happen, you should fire the programmer ;)";
		    return 0;
		  	break;
		}
	}
	function initialize($ini)
	{
		$ini_array 	= parse_ini_file($ini);
		foreach($ini_array as $key=>$val)
			$this->$key	= $val;
			
	}
	function __get($key)
	{
		$retval	= "";
		switch ($key)
		{
			case "FileName":
				$retval	= $this->cls_filename;
				break;
			case "URL":
				{
					$retval	= $this->cls_upload_dir;
					$retval	= SITE_VIRTUAL.substr($retval,strlen(DOCUMENTROOT)).$this->cls_filename;
				}
		}
		return $retval;
	}
	function __set($key,$val)
	{
		switch($key)
		{
			case "UPLOAD_FILE_TYPE":
			{
				$val = explode(",",$val);
				$len = count($val);
				for($i=0;$i<$len;$i++)
				{
					$val[$i]	= "." .$val[$i];
				}
				$this->cls_arr_ext_accepted = $val;
				break;
			}
			case "UPLOAD_FILE_MAX_SIZE":
				$this->cls_max_filesize	= $val;
				break;
			case "UPLOAD_FILE_CHECK_FILE_EXISTS":
				$this->cls_file_exists	= $val;
				break;
			case "UPLOAD_FILE_AUTO_RENAME":
				$this->cls_rename_file	= $val;
				break;
			case "UPLOAD_FILE_ERROR_TYPE":
				$this->cls_verbal		= $val;
				break;
			default:
				break;
		}
	}

}; // end class

// exemple
/*

if( $_POST['submit'] != '' ){

  $u = new MyUpload( $_FILES['image']['name'], $_FILES['image']['tmp_name'], $_FILES['image']['size'], "thisname" );
  $result = $u->upload( "../image/upload/" );
  print $result;

}

print "<br><br>\n";
print "<form enctype='multipart/form-data' method='post' action='". $PHP_SELF ."'>\n";
print "<input type='hidden' name='MAX_FILE_SIZE' value='200000'>\n";
print "<input type='file' name='image'>\n";
print "<input type='submit' value='Upload' name='submit'>\n";
print "</form>\n";
*/
?>